package com.mtiiot.fsmanage.server;


import com.mtiiot.fscore.utils.StringUtil;
import com.mtiiot.fsmanage.bean.parameter.User;
import com.mtiiot.fsmanage.core.dao.BaseElasticsearch;
import com.mtiiot.fsmanage.utils.Contants;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service
@Transactional
public class ParUserServer {
    private static String INDEX = Contants.INDEX_PARAMETER;
    private static String TYPE = Contants.TYPE_PARAMETER_USER;
    @Autowired
    private BaseElasticsearch baseElasticsearch;
	
	public User queryUser(String userName,String pwd) throws Exception{
        if(StringUtil.isEmpty(userName)){
            return null;
        }
        if(StringUtil.isEmpty(pwd)){
            return null;
        }
            Client client=null;
            try{
                client=baseElasticsearch.getEsDataSource().getClient();
                BoolQueryBuilder bq= QueryBuilders.boolQuery();
                bq.must(QueryBuilders.termQuery("userName", userName));                 // Query
                bq.must(QueryBuilders.termQuery("userPassword", pwd));                 // Query
                SearchRequestBuilder srb = client.prepareSearch(INDEX)
                        .setTypes(TYPE)
                        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                        .setExplain(true);
                // 最后就是返回搜索响应信息
                srb.setQuery(bq);
                SearchResponse response =srb.execute().actionGet();
                SearchHits searchHits = response.getHits();
                SearchHit[] hits = searchHits.getHits();
                if(hits.length==0){
                    return null;
                }
                Map<String, Object> sm=hits[0].sourceAsMap();
                User u=new User();
                u.setId(sm.get("id").toString());
                u.setUserName(sm.get("userName").toString());
                return u;
            }finally {
                if(client!=null){
                    baseElasticsearch.getEsDataSource().releaseClient(client);
                }
            }
    }
}
